﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace VersionComparer.Base
{
    public static class EventHandlerExtensions
    {
        /// <summary>
        /// Executes an eventhandler
        /// </summary>
        /// <typeparam name="T">type of eventhandler argument</typeparam>
        /// <param name="eventHandler">eventhandler to call</param>
        /// <param name="sender">event sender</param>
        /// <param name="args">event argument</param>
        public static void Execute<T>(this EventHandler<T> eventHandler, object sender , T args)
            where T : EventArgs 
        {
            EventHandler<T> handler = eventHandler;
            if ( handler != null )
                handler.Invoke(sender, args);
        }

        /// <summary>
        /// Executes an eventhandler
        /// </summary>
        /// <param name="eventHandler">eventhandler</param>
        /// <param name="sender">event sender</param>
        /// <param name="args">event argument</param>
        public static void Execute(this EventHandler eventHandler, object sender, EventArgs args)
        {
            EventHandler handler = eventHandler;
            if (handler != null)
                handler.Invoke(sender, args);
        }

        /// <summary>
        /// Executes an eventhandler
        /// </summary>
        /// <typeparam name="T">type of argument</typeparam>
        /// <param name="eventHandler">event</param>
        /// <param name="value">argument</param>
        /// <returns>event response</returns>
        public static GenericEventArgs<T> Execute<T>(this EventHandler<GenericEventArgs<T>> eventHandler, T value)
        {
            return Execute<T>(eventHandler, null, value);
        }
        /// <summary>
        /// Executes an eventhandler
        /// </summary>
        /// <typeparam name="T">type of argument</typeparam>
        /// <param name="eventHandler">eventhandler</param>
        /// <param name="sender">event sender</param>
        /// <param name="value">event argument</param>
        /// <returns>event response</returns>
        public static GenericEventArgs<T> Execute<T>(this EventHandler<GenericEventArgs<T>> eventHandler, object sender , T value)
        {
            EventHandler<GenericEventArgs<T>> eventHandlercopy = eventHandler;
            GenericEventArgs<T> result = new GenericEventArgs<T>(value);
            if (eventHandlercopy != null)
            {
                eventHandlercopy.Invoke(sender, result);
            }
            return result;
        }
    }
}
